package com.guojian.http.handle;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.util.EntityUtils;
import org.smartboot.http.HttpRequest;
import org.smartboot.http.HttpResponse;
import org.smartboot.http.enums.HttpStatus;
import org.smartboot.http.server.AbstractResponse;
import org.smartboot.http.server.HttpOutputStream;

public class HttpSmartResponseWrapper extends AbstractResponse {

	private HttpResponse smartHttpResponse;//smartHttp response

	private HttpRequest smartHttpRequest;

	private org.apache.http.HttpResponse closeableHttpResponse;//httpClient response

	public HttpSmartResponseWrapper(HttpResponse smartHttpResponse, HttpRequest smartHttpRequest, org.apache.http.HttpResponse closeableHttpResponse) {
		super();
		this.smartHttpResponse = smartHttpResponse;
		this.smartHttpRequest = smartHttpRequest;
		this.closeableHttpResponse = closeableHttpResponse;
		super.init(smartHttpRequest, (HttpOutputStream) smartHttpResponse.getOutputStream());
		initSmartHttpResponseHeaders(smartHttpResponse, closeableHttpResponse);
	}

	public void writeResponse() throws IOException {
		HttpEntity entity = getCloseableHttpResponse().getEntity();
		if (entity != null) {
			super.write(EntityUtils.toByteArray(entity));
		}
	}

	public void initSmartHttpResponseHeaders(HttpResponse smartHttpResponse, org.apache.http.HttpResponse closeableHttpResponse) {

		smartHttpResponse.setHttpStatus(HttpStatus.valueOf(closeableHttpResponse.getStatusLine().getStatusCode()));
		closeableHttpResponse.removeHeaders(HttpHeaders.LAST_MODIFIED);
		closeableHttpResponse.removeHeaders(HttpHeaders.ETAG);
		//closeableHttpResponse.setHeader(HttpHeaders.SERVER, "Fast_Http");
		closeableHttpResponse.removeHeaders(HttpHeaders.CONNECTION);

		Header[] headers = closeableHttpResponse.getAllHeaders();
		for (Header header : headers) {
			smartHttpResponse.addHeader(header.getName(), header.getValue());
		}
	}

	public HttpResponse getSmartHttpResponse() {
		return smartHttpResponse;
	}

	public void setSmartHttpResponse(HttpResponse smartHttpResponse) {
		this.smartHttpResponse = smartHttpResponse;
	}

	public HttpRequest getSmartHttpRequest() {
		return smartHttpRequest;
	}

	public void setSmartHttpRequest(HttpRequest smartHttpRequest) {
		this.smartHttpRequest = smartHttpRequest;
	}

	public org.apache.http.HttpResponse getCloseableHttpResponse() {
		return closeableHttpResponse;
	}

	public void setCloseableHttpResponse(org.apache.http.HttpResponse closeableHttpResponse) {
		this.closeableHttpResponse = closeableHttpResponse;
	}

}
